package dk.mitaffald.database;

import java.util.ArrayList;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import dk.mitaffald.maps.AbstractMapActivity;
import dk.tankegang.mitaffald.R;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class ViewCountry extends AbstractMapActivity implements OnNavigationListener, OnInfoWindowClickListener {
	
	private static final String STATE_NAV="nav";
	private static final int[] MAP_TYPE_NAMES= { R.string.normal, R.string.hybrid, R.string.satellite, R.string.terrain };
	private static final int[] MAP_TYPES= { GoogleMap.MAP_TYPE_NORMAL,
									GoogleMap.MAP_TYPE_HYBRID, GoogleMap.MAP_TYPE_SATELLITE,
									GoogleMap.MAP_TYPE_TERRAIN };
	private static final String TAG = "Leyth";
	private GoogleMap map=null;
	private long rowID;
	private TextView nameTv;
	private TextView capTv;
	private TextView codeTv; 
	private TextView city;
	private TextView mandag;
	private TextView tirsdag;
	private TextView onsdag;
	private TextView torsdag;
	private TextView fredag;
	private TextView lordag;
	private TextView sondag;
	private TextView lat_text;
	private TextView lng_text;
	   
	
	@Override
	public void onCreate(Bundle savedInstanceState) 
	   {
	    super.onCreate(savedInstanceState);
	    
	       if (readyToGo()) {
	          setContentView(R.layout.view_country);
  			
	        Bundle extras = getIntent().getExtras();
	        rowID = extras.getLong(CountryList.ROW_ID); 
	        
	        nameTv = (TextView) findViewById(R.id.nameText);
	  		capTv = (TextView) findViewById(R.id.capText);
	  		codeTv = (TextView) findViewById(R.id.codeText);
	  		city = (TextView) findViewById(R.id.codeCity);

	  		mandag = (TextView) findViewById(R.id.textVi1);
	  		tirsdag = (TextView) findViewById(R.id.textVi2);
	  		onsdag = (TextView) findViewById(R.id.textVi3);
	  		torsdag = (TextView) findViewById(R.id.textVi4);
	  		fredag = (TextView) findViewById(R.id.textVi5);
	  		lordag = (TextView) findViewById(R.id.textVi6);
	  		sondag = (TextView) findViewById(R.id.textVi7);
	  		lat_text= (TextView) findViewById(R.id.lat_fav);
	  		lng_text = (TextView) findViewById(R.id.lng_fav);
      
	       }
      }
	    
	   @Override
	   protected void onResume()
	   {
	      super.onResume();
	      new LoadContacts().execute(rowID);
	   } 
	   
	   private class LoadContacts extends AsyncTask<Long, Object, Cursor> 
	   {
	      DatabaseConnector dbConnector = new DatabaseConnector(ViewCountry.this);
	      
	      @Override
	      protected Cursor doInBackground(Long... params)
	      {
	         dbConnector.open();
		         return dbConnector.getOneContact(params[0]);
	      } 

	      @Override
	      protected void onPostExecute(Cursor result)
	      {
	         super.onPostExecute(result);
	   
	         result.moveToFirst();
	         // get the column index for each data item
	         int nameIndex = result.getColumnIndex("name");
	         int capIndex = result.getColumnIndex("address");
	         int codeIndex = result.getColumnIndex("postal");
	         
	         int codeCity = result.getColumnIndex("city");
	         
	         int man = result.getColumnIndex("monday");
	         int tirs = result.getColumnIndex("tuesday");
	         int ons = result.getColumnIndex("wednesday");
	         int tors = result.getColumnIndex("thursday");
	         int fre = result.getColumnIndex("friday");
	         int lor = result.getColumnIndex("saturday");
	         int son = result.getColumnIndex("sunday");
	         
	         int lat = result.getColumnIndex("lat");
	         int lng = result.getColumnIndex("lng");
	         
	   
	         nameTv.setText(result.getString(nameIndex));
	         capTv.setText(result.getString(capIndex));
	         codeTv.setText(result.getString(codeIndex));
	         city.setText(result.getString(codeCity));
	         
	         mandag.setText(result.getString(man));
	         tirsdag.setText(result.getString(tirs));
	         onsdag.setText(result.getString(ons));
	         torsdag.setText(result.getString(tors));
	         fredag.setText(result.getString(fre));
	         lordag.setText(result.getString(lor));
	         sondag.setText(result.getString(son));
	         
	         lat_text.setText(result.getString(lat));
	         lng_text.setText(result.getString(lng));
	         
	          
	         SupportMapFragment mapFrag= (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map_2);

		     initListNav();

		     map = mapFrag.getMap();

		     CameraUpdate center= CameraUpdateFactory.newLatLng(new LatLng(Double.valueOf(lat_text.getText().toString()), Double.valueOf(lng_text.getText().toString())));
		     CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);

		     map.moveCamera(center);
		     map.animateCamera(zoom);
		     
		     addMarker(map, Double.valueOf(lat_text.getText().toString()), Double.valueOf(lng_text.getText().toString()));
	         

		     
		     result.close();
	         dbConnector.close();
	      }
	   } 
	   

	   	   
	   private void deleteContact()
	   {
	     
	      AlertDialog.Builder alert = new AlertDialog.Builder(ViewCountry.this);

	      alert.setTitle(R.string.confirmTitle); 
	      alert.setMessage(R.string.confirmMessage); 

	      alert.setPositiveButton(R.string.delete_btn,
	         new DialogInterface.OnClickListener()
	         {
	            public void onClick(DialogInterface dialog, int button)
	            {
	               final DatabaseConnector dbConnector = 
	                  new DatabaseConnector(ViewCountry.this);

	               AsyncTask<Long, Object, Object> deleteTask =
	                  new AsyncTask<Long, Object, Object>()
	                  {
	                     @Override
	                     protected Object doInBackground(Long... params)
	                     {
	                        dbConnector.deleteContact(params[0]); 
	                        return null;
	                     } 
	                     
	                     @Override
	                     protected void onPostExecute(Object result)
	                     {
	                        finish(); 
	                     }
	                  };

	               deleteTask.execute(new Long[] { rowID });               
	            }
	         }
	      );
	      
	      alert.setNegativeButton(R.string.cancel_btn, null).show();
	   }
	   
	   
	   
	   @Override
	   public boolean onNavigationItemSelected(int itemPosition, long itemId) {
	     map.setMapType(MAP_TYPES[itemPosition]);

	     return(true);
	   }

	   @Override
	   public void onSaveInstanceState(Bundle savedInstanceState) {
	     super.onSaveInstanceState(savedInstanceState);
	     
	     savedInstanceState.putInt(STATE_NAV,
	                               getSupportActionBar().getSelectedNavigationIndex());
	   }
	   
	   @Override
	   public void onRestoreInstanceState(Bundle savedInstanceState) {
	     super.onRestoreInstanceState(savedInstanceState);
	     
	     getSupportActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_NAV));
	   }
	   
	   
	   private void initListNav() {
		    ArrayList<String> items=new ArrayList<String>();
		    ArrayAdapter<String> nav=null;
		    ActionBar bar=getSupportActionBar();

		    for (int type : MAP_TYPE_NAMES) {
		      items.add(getString(type));
		    }

		    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
		      nav=
		          new ArrayAdapter<String>(
		                                   bar.getThemedContext(),
		                                   android.R.layout.simple_spinner_item,
		                                   items);
		    }
		    else {
		      nav=
		          new ArrayAdapter<String>(
		                                   this,
		                                   android.R.layout.simple_spinner_item,
		                                   items);
		    }

		    nav.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		    bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
		    bar.setListNavigationCallbacks(nav, this);
		  }

		  private void addMarker(GoogleMap map, double lat, double lon) {
		    map.addMarker(new MarkerOptions().position(new LatLng(lat, lon))
		                        );
		  }

		@Override
		public void onInfoWindowClick(Marker marker) {
			Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();
		}
	}
